import { cloneDeep, isFunction, isMap, isObject, isString } from 'lodash';
import { BasicColumn, BasicTableProps, CellFormat, Recordable } from '../types';
import { ComputedRef, ref, watch, unref, computed } from 'vue';
import { dayjs } from 'element-plus';

export function formatCell(text: string, format: CellFormat, record: Recordable, index: number) {
  if (!format) {
    return text || (Number(text) == 0 && text !== '') ? text : '--';
  }

  // custom function
  if (isFunction(format)) {
    return format(text, record, index);
  }

  try {
    // date type
    const DATE_FORMAT_PREFIX = 'date|';
    if (isString(format) && format.startsWith(DATE_FORMAT_PREFIX) && text) {
      const dateFormat = format.replace(DATE_FORMAT_PREFIX, '');

      if (!dateFormat) {
        return text;
      }
      return dayjs(Number(text) * 1000).format(dateFormat);
    }

    // Map
    if (isMap(format)) {
      return format.get(text);
    }

    // object
    if (isObject(format)) {
      return format[text];
    }
  } catch (error) {
    return text;
  }
}

export function useColumns(props: ComputedRef<BasicTableProps>) {
  // 列数据
  const columns = ref<typeof props.value.columns>([]);
  const fields = ref<string[]>([]);
  const fixedFields = ref<string[]>([]);
  // 列数据
  watch(
    () => unref(props).columns,
    () => {
      columns.value = cloneDeep(unref(props).columns || []);
      fixedFields.value = [
        ...unref(columns)
          .filter((item) => item.clocked)
          .map((item) => item.prop ?? ''),
      ];
      fields.value = unref(columns)
        .map((item) => item.prop ?? '')
        .filter((item) => {
          if (!item) {
            return false;
          }
          if (fixedFields.value.includes(item)) {
            return false;
          }
          return true;
        });
    },
    {
      immediate: true,
    },
  );

  const getShowButton = computed(() => {
    return unref(columns).length > 6;
  });

  const getColumns = computed(() => {
    return unref(columns);
  });

  const getColumnsByFields = computed(() => {
    return unref(getColumns).filter((item) => {
      return [...unref(fixedFields), ...unref(fields)].includes(item.prop ?? '');
    });
  });

  const getCheckedColumns = computed(() => {
    return unref(getColumns).filter((item) => {
      return !unref(fixedFields).includes(item.prop ?? '');
    });
  });
  const setColumnByField = (field: string, column: BasicColumn<any>) => {
    const index = unref(getColumns).findIndex((item) => {
      return item.prop === field;
    });
    if (index !== -1) {
      unref(getColumns)[index] = { ...unref(getColumns)[index], ...column };
    }
  };

  const setColumns = (columns: BasicColumn<any>[]) => {
    unref(getColumns).splice(0, unref(getColumns).length, ...columns);
  };

  return {
    fields,
    getColumns,
    getCheckedColumns,
    getColumnsByFields,
    getShowButton,
    setColumnByField,
    setColumns,
  };
}
